// pages/order/order.js
const { post } = require("../../utils/request");
const { handleGlobalError } = require("../../utils/globalErrorHandler");
const { getOrderStatusCount } = require("../../api/order");

Page({
  data: {
    // 当前选中的标签
    currentTab: "all",
    // 订单标签配置
    orderTabs: [
      { label: "全部", value: "all", count: 0 },
      { label: "待支付", value: "pending", count: 0 },
      { label: "待发货", value: "shipping", count: 0 },
      { label: "待收货", value: "delivered", count: 0 },
      { label: "售后", value: "refund", count: 0 },
    ],
    // 订单类型选项
    orderTypeOptions: [
      { label: "全部", value: null },
      { label: "普通", value: 1 },
      { label: "满减", value: 2 },
      { label: "折扣", value: 3 },
      { label: "特价", value: 4 },
    ],
    // 选中的订单类型
    selectedOrderType: null,
    // 搜索关键词
    searchKeyword: "",
    // 订单列表
    orderList: [],
    // 分页信息
    pageInfo: {
      pageIndex: 1,
      pageSize: 10,
      hasMore: true,
      total: 0,
    },
    // 加载状态
    loading: false,
    refreshing: false,
  },

  onLoad() {
    this.loadOrderList(true);
    this.loadOrderStatusCount();
  },

  onShow() {
    // 主动更新TabBar选中状态
    const app = getApp();
    app.updateCustomTabBar();

    // 重新启动倒计时定时器
    this.startCountdownTimer();
  },

  onHide() {
    // 清理倒计时定时器
    if (this.countdownTimer) {
      clearInterval(this.countdownTimer);
      this.countdownTimer = null;
    }
  },

  onUnload() {
    // 页面卸载时清理定时器
    if (this.countdownTimer) {
      clearInterval(this.countdownTimer);
      this.countdownTimer = null;
    }
  },

  // 加载订单状态统计
  async loadOrderStatusCount() {
    try {
      const res = await getOrderStatusCount(this.data.selectedOrderType);
      if (res.code === 0) {
        const { pending, shipping, delivered, refund } = res.data;

        // 更新标签计数（不包括全部，全部的数量从queryOrders接口获取）
        const orderTabs = this.data.orderTabs.map((tab) => {
          let count = tab.count; // 保持原有计数
          switch (tab.value) {
            case "pending":
              count = pending || 0;
              break;
            case "shipping":
              count = shipping || 0;
              break;
            case "delivered":
              count = delivered || 0;
              break;
            case "refund":
              count = refund || 0;
              break;
            case "all":
              // 全部的数量保持原值，由loadOrderList方法更新
              break;
            default:
              count = 0;
          }
          return {
            ...tab,
            count: count,
          };
        });

        this.setData({ orderTabs });
      }
    } catch (error) {
      console.error("获取订单状态统计失败:", error);
      // 不显示错误提示，避免影响用户体验
    }
  },

  // 加载订单列表
  async loadOrderList(isRefresh = false) {
    if (this.data.loading) return;

    const { currentTab, pageInfo, selectedOrderType, searchKeyword } =
      this.data;

    // 构建请求参数
    const params = {
      orderType: selectedOrderType,
      spuName: searchKeyword,
      pageIndex: isRefresh ? 1 : pageInfo.pageIndex,
      pageSize: pageInfo.pageSize,
    };

    // 根据当前标签设置订单状态
    if (currentTab !== "all") {
      params.orderStatus = this.getOrderStatusByTab(currentTab);
    }

    try {
      this.setData({
        loading: true,
        refreshing: isRefresh,
      });

      const res = await post("/client/order/queryOrders", params);

      if (res.code === 0) {
        const { list, total, hasNextPage } = res.data;

        // 处理商品规格文本和订单类型文本
        const processedList = list.map((order) => {
          // 处理订单类型文本
          order.orderTypeText = this.getOrderTypeText(order.orderType);

          // 处理支付倒计时
          order.showCountdown = this.shouldShowCountdown(
            order.orderStatus,
            order.payExpireTime
          );
          order.countdownText = this.getCountdownText(order.payExpireTime);

          // 处理商品规格文本
          if (order.itemVOS && order.itemVOS.length > 0) {
            order.itemVOS = order.itemVOS.map((item) => {
              if (item.skuSpecs && !item.specsText) {
                item.specsText = this.parseSpecText(item.skuSpecs);
              }
              return item;
            });
          }
          return order;
        });

        this.setData({
          orderList: isRefresh
            ? processedList
            : [...this.data.orderList, ...processedList],
          "pageInfo.pageIndex": isRefresh ? 2 : pageInfo.pageIndex + 1,
          "pageInfo.hasMore": hasNextPage,
          "pageInfo.total": total,
        });

        // 更新"全部"标签的数量
        this.updateAllTabCount(total);

        // 启动倒计时定时器
        this.startCountdownTimer();
      }
    } catch (error) {
      handleGlobalError(error);
    } finally {
      this.setData({
        loading: false,
        refreshing: false,
      });
    }
  },

  // 更新"全部"标签的数量
  updateAllTabCount(total) {
    const orderTabs = this.data.orderTabs.map((tab) => {
      if (tab.value === "all") {
        return {
          ...tab,
          count: total > 99 ? "10+" : total || 0,
        };
      }
      return tab;
    });
    this.setData({ orderTabs });
  },

  // 根据标签获取订单状态
  getOrderStatusByTab(tab) {
    const statusMap = {
      pending: [0, 11, 12], // 待支付（待付款、支付中、支付失败）
      shipping: [1, 3], // 待发货（已付款、已出库）
      delivered: [4], // 待收货（已发货）
      refund: [6, 7, 8], // 售后（申请售后、部分退款、全部退款）
      completed: [9, 10], // 已完成（确认收货、已完成）
      closed: [2, 5], // 已关闭（支付超时、已取消）
    };
    return statusMap[tab] || [];
  },

  // 标签切换
  onTabChange(e) {
    const tab = e.currentTarget.dataset.tab;
    if (tab === this.data.currentTab) return;

    this.setData({ currentTab: tab });
    this.loadOrderList(true);
  },

  // 搜索输入
  onSearchInput(e) {
    this.setData({
      searchKeyword: e.detail.value,
    });
  },

  // 搜索确认
  onSearchConfirm() {
    this.loadOrderList(true);
  },

  // 清除搜索
  onClearSearch() {
    this.setData({
      searchKeyword: "",
    });
    this.loadOrderList(true);
  },

  // 订单类型筛选
  onOrderTypeChange(e) {
    const orderType = e.currentTarget.dataset.type;
    if (orderType === this.data.selectedOrderType) return;

    this.setData({
      selectedOrderType: orderType === "null" ? null : parseInt(orderType),
    });
    this.loadOrderList(true);
    this.loadOrderStatusCount();
  },

  // 下拉刷新
  onRefresh() {
    this.loadOrderList(true);
    this.loadOrderStatusCount();
  },

  // 上拉加载更多
  onLoadMore() {
    if (this.data.pageInfo.hasMore && !this.data.loading) {
      this.loadOrderList(false);
    }
  },

  // 获取状态样式类
  getStatusClass(status) {
    if ([0, 11, 12].includes(status)) return "pending";
    if ([1, 3].includes(status)) return "shipping";
    if (status === 4) return "delivered";
    if ([6, 7, 8].includes(status)) return "refund";
    if ([9, 10].includes(status)) return "completed";
    if ([2, 5].includes(status)) return "closed";
    return "pending";
  },

  // 获取状态文本
  getStatusText(status) {
    const statusMap = {
      0: "待付款",
      1: "已付款",
      2: "支付超时",
      3: "已出库",
      4: "已发货",
      5: "已取消",
      6: "申请售后",
      7: "部分退款",
      8: "全部退款",
      9: "确认收货",
      10: "已完成",
      11: "支付中",
      12: "支付失败",
    };
    return statusMap[status] || "未知状态";
  },

  // 解析商品规格文本 - 使用和商品详情页面相同的逻辑
  parseSpecText(specs) {
    try {
      const specObj = JSON.parse(specs);
      const specArray = [];

      for (const key in specObj) {
        if (Array.isArray(specObj[key])) {
          specArray.push(`${key}: ${specObj[key].join(", ")}`);
        } else {
          specArray.push(`${key}: ${specObj[key]}`);
        }
      }

      return specArray.join(" | ");
    } catch (error) {
      console.error("解析规格失败:", error);
      return specs;
    }
  },

  // 获取订单类型文本
  getOrderTypeText(orderType) {
    const typeMap = {
      1: "普通",
      2: "满减",
      3: "折扣",
      4: "特价",
    };
    return typeMap[orderType] || "";
  },

  // 判断是否显示倒计时
  shouldShowCountdown(orderStatus, payExpireTime) {
    if (!payExpireTime) return false;
    const pendingStatuses = [0, 11, 12]; // 待支付状态
    if (!pendingStatuses.includes(orderStatus)) return false;

    const now = new Date().getTime();
    // 转换日期格式以兼容iOS
    const formattedTime = payExpireTime.replace(/-/g, "/");
    const expireTime = new Date(formattedTime).getTime();
    return expireTime > now;
  },

  // 获取倒计时文本
  getCountdownText(payExpireTime) {
    if (!payExpireTime) return "";

    const now = new Date().getTime();
    // 转换日期格式以兼容iOS
    const formattedTime = payExpireTime.replace(/-/g, "/");
    const expireTime = new Date(formattedTime).getTime();
    const diff = expireTime - now;

    if (diff <= 0) return "已超时";

    const minutes = Math.floor(diff / (1000 * 60));
    const seconds = Math.floor((diff % (1000 * 60)) / 1000);

    return `剩余${minutes}分${seconds}秒`;
  },

  // 启动倒计时定时器
  startCountdownTimer() {
    if (this.countdownTimer) {
      clearInterval(this.countdownTimer);
    }

    this.countdownTimer = setInterval(() => {
      const orderList = this.data.orderList;
      let needUpdate = false;

      const updatedOrderList = orderList.map((order) => {
        if (order.showCountdown) {
          const newCountdownText = this.getCountdownText(order.payExpireTime);
          if (newCountdownText !== order.countdownText) {
            order.countdownText = newCountdownText;
            needUpdate = true;
          }

          // 检查是否已超时
          if (newCountdownText === "已超时") {
            order.showCountdown = false;
            needUpdate = true;
          }
        }
        return order;
      });

      if (needUpdate) {
        this.setData({ orderList: updatedOrderList });
      }
    }, 1000);
  },

  // 判断支付是否超时
  isPayExpired(payExpireTime) {
    if (!payExpireTime) return false;
    const now = new Date().getTime();
    const expireTime = new Date(payExpireTime).getTime();
    return now < expireTime;
  },

  // 支付订单
  onPayOrder(e) {
    const order = e.currentTarget.dataset.order;
    wx.showToast({
      title: "跳转到支付页面",
      icon: "none",
    });
    // TODO: 实现支付逻辑
  },

  // 取消订单
  onCancelOrder(e) {
    const order = e.currentTarget.dataset.order;
    wx.showModal({
      title: "确认取消",
      content: "确定要取消这个订单吗？",
      success: (res) => {
        if (res.confirm) {
          wx.showToast({
            title: "订单已取消",
            icon: "success",
          });
          // TODO: 调用取消订单接口
        }
      },
    });
  },

  // 确认收货
  onConfirmReceive(e) {
    const order = e.currentTarget.dataset.order;
    wx.showModal({
      title: "确认收货",
      content: "确定已收到商品吗？",
      success: (res) => {
        if (res.confirm) {
          wx.showToast({
            title: "确认收货成功",
            icon: "success",
          });
          // TODO: 调用确认收货接口
        }
      },
    });
  },

  // 查看订单详情
  onViewOrderDetail(e) {
    const order = e.currentTarget.dataset.order;
    wx.navigateTo({
      url: `/pages/order-detail/order-detail?orderId=${order.id}`,
    });
  },

  // 去购物
  onGoShopping() {
    wx.switchTab({
      url: "/pages/index/index",
    });
  },

  // 申请退款
  onApplyRefund(e) {
    const order = e.currentTarget.dataset.order;
    wx.showModal({
      title: "申请退款",
      content: "确定要申请退款吗？",
      success: (res) => {
        if (res.confirm) {
          // TODO: 调用申请退款接口
          wx.showToast({
            title: "退款申请已提交",
            icon: "success",
          });
        }
      },
    });
  },

  // 申请售后
  onApplyAfterSale(e) {
    const order = e.currentTarget.dataset.order;
    wx.showModal({
      title: "申请售后",
      content: "确定要申请售后吗？",
      success: (res) => {
        if (res.confirm) {
          // TODO: 调用申请售后接口
          wx.showToast({
            title: "售后申请已提交",
            icon: "success",
          });
        }
      },
    });
  },

  // 取消售后
  onCancelAfterSale(e) {
    const order = e.currentTarget.dataset.order;
    wx.showModal({
      title: "取消售后",
      content: "确定要取消售后吗？",
      success: (res) => {
        if (res.confirm) {
          // TODO: 调用取消售后接口
          wx.showToast({
            title: "售后已取消",
            icon: "success",
          });
        }
      },
    });
  },

  // 再次购买
  onBuyAgain(e) {
    const order = e.currentTarget.dataset.order;
    // TODO: 跳转到商品页面或购物车
    wx.showToast({
      title: "跳转到商品页面",
      icon: "success",
    });
  },
});
